import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

# 预共享密钥和初始化向量(必须与服务端一致)
key = b'abcdefghijklmnopqrstuvwxyz123456'  # 32字节密钥
iv = b'1234567890abcdef'  # 16字节初始化向量


def encrypt_file(file_path):
    """读取文件内容并加密"""
    try:
        with open(file_path, 'rb') as f:
            plaintext = f.read()

        cipher = AES.new(key, AES.MODE_CBC, iv)
        ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
        return ciphertext

    except Exception as e:
        print(f"加密错误: {e}")
        return None


def send_encrypted_file(server_ip, server_port, file_path):
    """连接服务器并发送加密文件"""
    # 创建TCP套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 连接服务器
        server_address = (server_ip, server_port)
        client_socket.connect(server_address)
        print(f"已连接到服务器 {server_ip}:{server_port}")

        # 加密文件
        encrypted_data = encrypt_file(file_path)
        if encrypted_data:
            # 发送加密数据
            client_socket.sendall(encrypted_data)
            print(f"已成功发送 {len(encrypted_data)} 字节的加密数据")
        else:
            print("加密失败，未发送数据")

    except Exception as e:
        print(f"发送过程中出错: {e}")
    finally:
        # 关闭连接
        client_socket.close()
        print("连接已关闭")


if __name__ == "__main__":
    # 服务器地址和端口
    server_ip = '192.168.1.100'  # 请替换为实际服务器IP
    server_port = 9999

    # 要发送的文件路径
    file_to_send = 'test.txt'

    # 发送加密文件
    send_encrypted_file(server_ip, server_port, file_to_send)